﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BingWallpaper
{
    public partial class Form1 : Form
    {
        const int windowWidth = 345, windowHeight = 190;
        readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        BingWallpaper bw = null;

        public Form1(bool autoRun)
        {
            InitializeComponent();
            Application.ThreadException += (o, e) => MessageBox.Show(e.Exception.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

            Size = new Size(windowWidth, windowHeight); //窗口大小
            TopMost = true;     //窗口最前
            SetFormLocation();       //窗口位置
            Text = "BingWallpaper";
            label1.Text = "壁纸";
            labelTitle.Text = "...";
            labelUp.Text = "<  上一个";
            labelDown.Text = "下一个  >";
            notifyIcon1.Text = this.Text;
            contextMenuStrip1.BackColor = BackColor;
            contextMenuStrip1.ForeColor = ForeColor;
            pictureBoxImg.Enabled = false;
            labelTitle.Enabled = false;
            labelUp.Enabled = false;
            labelDown.Enabled = false;
            ShowInTaskbar = false;
            SetToolTip();  //工具按钮提示
            每日更新壁纸ToolStripMenuItem.Checked = AutoRun.State;  //自动运行

            //启动延时
            var startTime = 1;
            //开机自动启动
            if (autoRun)
            {
                WindowState = FormWindowState.Minimized;  //最小化
                startTime = 15000;  //等待15秒
            }

            //定时器 
            timer.Interval = startTime;
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            //计算到下一个9:05的时间差
            DateTime now = DateTime.Now;
            DateTime date = now.Hour < 9 ? now.Date : now.Date.AddDays(1);
            TimeSpan duration = date.AddHours(9).AddMinutes(5) - now;
            timer.Interval = (int)duration.TotalMilliseconds;

            var newBW = new BingWallpaper();
            if (!newBW.Equals(bw))
            {
                bw = newBW;
                SetPicAndLabel();
            }
        }

        private void SetPicAndLabel()
        {
            pictureBoxImg.Enabled = true;
            labelTitle.Enabled = true;
            labelDown.Enabled = bw.Index > 0;
            labelUp.Enabled = bw.Index < bw.Count - 1;

            var data = bw.CurrentData;
            if (data == null) return;
            labelTitle.Text = data.Headline;
            labelTitle.Tag = data.Copyrightlink;
            var file = data.GetImageFile();
            if (!string.IsNullOrEmpty(file))
            {
                using (var image = Image.FromFile(file))
                {
                    pictureBoxImg.Image = image.GetThumbnailImage(128, 72, null, IntPtr.Zero);
                    pictureBoxImg.Tag = file;                    
                }
                SetBackground(file);
            }
            else
            {
                pictureBoxImg.Image = new Bitmap(128, 72);
            }
        }

        //定义ToolTip对象
        private void SetToolTip()
        {
            ToolTip toolTip = new ToolTip();
            toolTip.SetToolTip(this.pictureBox_Bing, "转至 Bing.com");
            toolTip.SetToolTip(this.pictureBox1, "最小化");
            toolTip.SetToolTip(this.pictureBox2, "设置");
            toolTip.SetToolTip(this.pictureBoxImg, "打开图片\r\n此图像只能用于壁纸");
            toolTip.SetToolTip(this.labelTitle, "在 Bing.com 上搜索");
            toolTip.SetToolTip(this.labelUp, "上一个图像");
            toolTip.SetToolTip(this.labelDown, "下一个图像");
        }

        //LOGO
        private void pictureBox_Bing_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, "http://www.bing.com");
        }

        //最小化
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            //this.WindowState = FormWindowState.Minimized;
            Hide();
        }

        //设置按钮
        private void pictureBox2_Click(object sender, EventArgs e)
        {
            var x = Location.X + ClientSize.Width - contextMenuStrip1.Size.Width;
            var y = Location.Y + panel1.Height;
            contextMenuStrip1.Show(x, y);
        }

        //通知栏图标
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            SetFormLocation();
            WindowState = FormWindowState.Normal;
            Show();
        }

        //窗体显示位置
        private void SetFormLocation()
        {
            int x = Screen.PrimaryScreen.WorkingArea.Size.Width - windowWidth - 15;
            int y = Screen.PrimaryScreen.WorkingArea.Size.Height - windowHeight - 15;
            Location = new Point(x, y);
        }

        #region 鼠标进入退出效果
        private void Control_MouseEnter(object sender, EventArgs e)
        {
            (sender as Control).BackColor = Color.FromArgb(140, 140, 140);
        }

        private void Control_MouseLeave(object sender, EventArgs e)
        {
            (sender as Control).BackColor = (sender as Control).Parent.BackColor;
        }

        private void labelTitle_MouseEnter(object sender, EventArgs e)
        {
            labelTitle.Font = new Font(Font.Name, Font.Size, FontStyle.Underline);
        }

        private void labelTitle_MouseLeave(object sender, EventArgs e)
        {
            labelTitle.Font = this.Font;
        }
        #endregion

        #region 点击事件
        private void pictureBoxImg_Click(object sender, EventArgs e)
        {
            if (pictureBoxImg.Tag is string file) Process.Start("explorer.exe", $"/select,{file}");
        }

        private void labelTitle_Click(object sender, EventArgs e)
        {
            if (labelTitle.Tag is string link) Help.ShowHelp(this, link);
        }

        private void labelUp_Click(object sender, EventArgs e)
        {
            bw.Index++;
            SetPicAndLabel();
        }

        private void labelDown_Click(object sender, EventArgs e)
        {
            bw.Index--;
            SetPicAndLabel();
        }
        #endregion

        #region 设置菜单
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, "https://gitee.com/zhux3/bing-wallpaper");
        }

        private void 每日更新壁纸ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AutoRun.State = !AutoRun.State;
            每日更新壁纸ToolStripMenuItem.Checked = AutoRun.State;
        }
        #endregion


        #region 标题栏托动
        [DllImport("user32.dll")]
        static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        const int WM_SYSCOMMAND = 0x0112;
        const int SC_MOVE = 0xF010;
        const int HTCAPTION = 0x0002;
        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }
        #endregion


        #region  设置背景
        public void SetBackground(string fileName)
        {
            try
            {
                using (var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true))
                {
                    //墙纸模式，填充
                    key.SetValue("TileWallpaper", "0");
                    key.SetValue("WallpaperStyle", "10");
                }
                Task.Run(() => SystemParametersInfo(20, 0, fileName, 3));
            }
            catch (Exception)
            {
                //throw;
            }
        }

        [DllImport("user32.dll", CharSet = CharSet.Unicode)]
        static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
        #endregion
    }


}
